package com.ztorn.security;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.ztorn.dtos.LoginRequest;
import com.ztorn.model.User;
import com.ztorn.utils.JwtUtils;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class JwtAuthenticationFilter extends UsernamePasswordAuthenticationFilter {

     private final AuthenticationManager authenticationManager;

     private final JwtUtils jwtUtil;

     public JwtAuthenticationFilter(AuthenticationManager authenticationManager, JwtUtils jwtUtil) {
         this.authenticationManager = authenticationManager;
         this.jwtUtil = jwtUtil;
         super.setFilterProcessesUrl("/api/login");
     }

     @Override
     public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException {
         try {
            LoginRequest loginRequest = new ObjectMapper().readValue(request.getInputStream(), LoginRequest.class);
             UsernamePasswordAuthenticationToken usernamePasswordAuthenticationToken = new UsernamePasswordAuthenticationToken(loginRequest.getAccount(), loginRequest.getPassword());
             Authentication authenticate = authenticationManager.authenticate(usernamePasswordAuthenticationToken);
             return authenticate;
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
     }

     @Override
     protected void successfulAuthentication(HttpServletRequest request, HttpServletResponse response, FilterChain chain, Authentication authResult) throws IOException, ServletException {
         User user = (User) authResult.getPrincipal();
         String token = jwtUtil.generateJwt(user.getUsername(), user.getRoleid().split(","));
         response.addHeader("Authorization", "Bearer " + token);
     }

    public static void main(String[] args) {

    }
}
